package com.demo.bluetooth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.demo.bluetooth.databinding.ActivityMainBinding;
import com.smasher.bluetooth.connect.BaseConnect;
import com.smasher.bluetooth.connect.BleConnectionListener;
import com.smasher.bluetooth.connect.ConnectBle;
import com.smasher.bluetooth.fragment.DeviceSelector;

import java.util.Arrays;


public class MainActivity extends AppCompatActivity {

    public static final String TAG = "BLUETOOTH";


    private ActivityMainBinding mainBinding;

    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;


    private final String[] permissions = new String[]{
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    @RequiresApi(api = Build.VERSION_CODES.S)
    private final String[] permission30above = new String[]{
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_ADVERTISE
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        Log.e(TAG, "onCreate: ");
        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initView();
        initBlueAdapter();
        checkBluetoothPermission();
    }


    private void initView() {

        mainBinding.contentContainer.discovering.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View v) {
                showSelectDevice();
            }
        });

        mainBinding.contentContainer.open.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View v) {
                checkBluetoothPermission();
            }
        });

        mainBinding.contentContainer.close.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View v) {
                disableBluetooth();
            }
        });
    }


    private void showSelectDevice() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag("DeviceSelector");
        if (fragment == null) {
            fragment = DeviceSelector.newInstance();
        }
        if (fragment instanceof DeviceSelector deviceSelector) {
            deviceSelector.setOnSelectListener(new DeviceSelector.OnSelectListener() {
                @SuppressLint("MissingPermission")
                @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
                @Override
                public void onSelect(BluetoothDevice device) {
                    Toast.makeText(MainActivity.this, "选择成功：" + device.getName(), Toast.LENGTH_SHORT).show();
                    initConnect(device);
                }
            });
            if (!deviceSelector.isShowing()) {
                deviceSelector.show(fragmentManager, "DeviceSelector");
            }
        }
    }


    private void checkBluetoothPermission() {
        String[] bluetoothPermissions = Build.VERSION.SDK_INT > Build.VERSION_CODES.R ? permission30above : permissions;
        boolean isAllGranted = true;
        for (String permission : bluetoothPermissions) {
            int result = ContextCompat.checkSelfPermission(this, permission);
            if (result != PackageManager.PERMISSION_GRANTED) {
                isAllGranted = false;
            }
            boolean logResult = result == PackageManager.PERMISSION_GRANTED;
            Log.e(TAG, "checkBluetoothPermission: " + permission + "-result=" + logResult);
        }
        if (isAllGranted) {
            enableBluetooth();
        } else {
            requestPermission();
        }
    }


    private void initBlueAdapter() {
        bluetoothManager = getSystemService(BluetoothManager.class);
    }

    @RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT})
    private void enableBluetooth() {
        //蓝牙适配器
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();
        } else {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
                bluetoothAdapter.enable();
            } else {
                Toast.makeText(this, "请开启蓝牙", Toast.LENGTH_SHORT).show();
                enableBluetoothLauncher.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
            }
        }
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    private void disableBluetooth() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            boolean result = bluetoothAdapter.disable();
            Log.e(TAG, "关闭蓝牙结果: " + result);
        }
    }

    private void requestPermission() {
        String[] bluetoothPermissions = Build.VERSION.SDK_INT > Build.VERSION_CODES.R ? permission30above : permissions;
        Log.e(TAG, "requestPermission: " + Arrays.toString(bluetoothPermissions));
        requestPermissionLauncher.launch(bluetoothPermissions);
    }

    private final ActivityResultLauncher<String[]> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), map -> {
                boolean isAllGranted = true;
                for (String key : map.keySet()) {
                    boolean keyValue = Boolean.TRUE.equals(map.get(key));
                    Log.e(TAG, key + ": " + keyValue);
                    if (!keyValue) {
                        isAllGranted = false;
                    }
                }
                afterRequestPermission(isAllGranted);
            });

    @SuppressLint("MissingPermission")
    private final ActivityResultLauncher<Intent> enableBluetoothLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == RESULT_OK) {
                    Toast.makeText(this, "请继续执行操作", Toast.LENGTH_SHORT).show();
                    enableBluetooth();
                }
            });

    @SuppressLint("MissingPermission")
    private void afterRequestPermission(boolean isAllGranted) {
        Log.e(TAG, "afterRequestPermission: " + isAllGranted);
        if (!isAllGranted) {
            return;
        }
        Toast.makeText(this, "请继续操作", Toast.LENGTH_SHORT).show();
    }


    private BaseConnect  baseConnect;


    @RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT})
    private void initConnect(BluetoothDevice device){
        baseConnect = new ConnectBle(this);
        baseConnect.setConnectionListener(new BleConnectionListener() {
            @Override
            public void onConnected(BluetoothDevice device) {
                Log.i(TAG, "onConnected: ");
            }

            @Override
            public void onDisconnected(BluetoothDevice device) {
                Log.i(TAG, "onDisconnected: ");
            }

            @Override
            public void onPairingRequested(BluetoothDevice device, int variant) {
                Log.i(TAG, "onPairingRequested: ");
            }

            @Override
            public void onPairingSuccess(BluetoothDevice device) {
                Log.i(TAG, "onPairingSuccess: ");
            }
        });
        baseConnect.init(this);

        baseConnect.connectDeviceImmediately(this, device);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (baseConnect != null) {
            baseConnect.release(this);
        }
    }

}